/**
 * 游戏登录/配置界面
 */
class Login extends eui.Component implements  eui.UIComponent {
	
	private btn_start: eui.Button;

	public constructor() {
		super();
		this.addMsResponseListen();
	}
	

	protected partAdded(partName:string,instance:any):void
	{
		this.getMyChilds(partName,instance);
		super.partAdded(partName,instance);
	}
	private getMyChilds(partName:string,instance:any){
		if("btn_start" == partName){
			this.btn_start = instance;
			this.btn_start.addEventListener(egret.TouchEvent.TOUCH_TAP, this.startGame, this);
		}
	}

	protected childrenCreated():void
	{
		super.childrenCreated();
	}
	//添加Matchvs初始化、用户注册、用户登录
	private addMsResponseListen(){
        mvs.MsResponse.getInstance.addEventListener(mvs.MsEvent.EVENT_INIT_RSP, this.initResponse,this);
        mvs.MsResponse.getInstance.addEventListener(mvs.MsEvent.EVENT_REGISTERUSER_RSP, this.registerUserResponse,this);
        mvs.MsResponse.getInstance.addEventListener(mvs.MsEvent.EVENT_LOGIN_RSP, this.loginResponse,this);
    }

    private release(){
        mvs.MsResponse.getInstance.removeEventListener(mvs.MsEvent.EVENT_INIT_RSP, this.initResponse,this);
        mvs.MsResponse.getInstance.removeEventListener(mvs.MsEvent.EVENT_REGISTERUSER_RSP, this.registerUserResponse,this);
        mvs.MsResponse.getInstance.removeEventListener(mvs.MsEvent.EVENT_LOGIN_RSP, this.loginResponse,this);
    }
	private startGame(){
		console.log(" environment=" + GameData.DEFAULT_ENV + " gameid=" + GameData.gameID);
		let result = mvs.MsEngine.getInstance.init(GameData.CHANNEL, GameData.DEFAULT_ENV, GameData.gameID, GameData.appkey);
	}
	//初始化 回调
	private initResponse(ev:egret.Event) {
        console.log("initResponse,Event:" + ev);
        if( ev.data.status !== 200){
            console.log("init failed", ev.data.status);
            return;
        }
        //获取微信信息
        this.getUserFromWeChat((userInfos)=>{
            //绑定 微信 openID 成功 生成一个 专用 userID 登录
            Login.bindOpenIDWithUserID(userInfos);
        },(res)=>{
            //获取微信信息失败，注册游客身份登录
            console.info("获取信息失败：",res);
            mvs.MsEngine.getInstance.registerUser();
        });
    }
	//matchvs 注册接口回调
    private registerUserResponse(ev:egret.Event) {
		 console.log("registerUserResponse,Event:",ev);
        let userInfo = ev.data;
        GameData.gameUser.id = userInfo.id;
        GameData.gameUser.name = userInfo.name;
        GameData.gameUser.avatar = userInfo.avatar;
        GameData.gameUser.token = userInfo.token;
        //登录
        if(userInfo.status == 0){
            mvs.MsEngine.getInstance.login(userInfo.id, userInfo.token);
        }
    }
	//matchvs login 接口回调处理
    private loginResponse(ev:egret.Event) {
		console.log("loginResponse, Event:" + ev);
        //MvsHttpApi.TestApi();
        mvs.MsResponse.getInstance.removeEventListener(mvs.MsEvent.EVENT_LOGIN_RSP, this.loginResponse,this);
        let login = ev.data;
        if (login.status != 200) {
            console.log("登陆失败");
        } else {
            console.log("登陆成功 roomID=" + login.roomID);
            if (login.roomID !== "0") {
                GameData.roomID = login.roomID;
                //重新连接
				console.log("登录出现错误，login.roomID=" + login.roomId);
				//暂未实现
                GameSceneView._gameScene.reconnectView();
            } else {
                GameSceneView._gameScene.lobby();
            }
        }
    }
	 /**
     * 绑定微信OpenID 返回用户信息
     */
    private static bindOpenIDWithUserID(wxUserInfo:any){
        console.log("获取到的微信用户信息",wxUserInfo);
        if(!wxUserInfo){
            return;
        }
        let mvshttp:MvsHttpApi = new MvsHttpApi();
        mvshttp.thirdBind(wxUserInfo.openInfo.openid, wxUserInfo.openInfo.session_key, (res, err)=>{
            if(res !== null){
                let repData = res;
                if (repData.status == 0){
                    console.log("绑定接口调用成功", res);
                    GameData.gameUser.id = repData.data.userid;
                    GameData.gameUser.name = wxUserInfo.userInfo.nickName;
                    GameData.gameUser.avatar = wxUserInfo.userInfo.avatarUrl;
                    GameData.gameUser.token = repData.data.token;
                    //绑定成功就登录
                    mvs.MsEngine.getInstance.login(GameData.gameUser.id, GameData.gameUser.token);
                }else{
                    console.log("bindOpenIDWithUserID get error : " , err);
                }
            }else{
                console.log("bindOpenIDWithUserID get error : " , err);
            }
        });
    }
	/**
     * 获取微信中的用户信息,这个是支持微信用户绑定的，如果使用微信身份登录，将执行绑定操作，如果是游客身份登录将到 matchvs 生成一个游客身份的userID
     */
    private getUserFromWeChat(success:Function, fa:Function){
        //获取微信信息
        try {
            let wxm = new Wxmodel();
            wxm.getWxUserInfo({
                success:(userInfos)=>{
                    console.log("获取用户信息成功！");
                    //获取OpenID
                    wxm.getUserOpenID({
                        success:function(openInfos){
                            console.info("openInfos:",openInfos);
                            if(openInfos.status == 0){
                                success({userInfo:userInfos, openInfo:openInfos.data});
                                //console.info("userInfo:",userInfos,"openInfo:",openInfos.data);
                            }else{
                                fa("获取OpenID失败！");
                            }
                        },
                        fail:(res)=>{
                                console.info("获取openID 失败！:",res);
                                fa(res);
                        }
                    });
                },
                fail:fa
            });
        } catch (error) {
            console.log("不是在微信平台，调用不进行绑定！");
            fa(error);
        }
    }
	
}